#!/bin/bash
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# Test and report code coverage.

source "$(dirname "$0")/common_lib.sh"
init_py_env

# Add trap to ensure coverage is reported even if script exits early
trap "coverage combine && coverage report" EXIT

run-ani-tests() {
    echo "Running ANI tests..."

    cd ..
    if [ -d "build" ]; then
        echo "Build directory found. Skipping CMake configuration."
    else
        echo "Build directory not found. Configuring with CMake."
        cmake -B build -GNinja -DENABLE_COVERAGE=ON
    fi
    cmake --build build --verbose
    cd compiler
}

run-core-tests() {
    echo "Running core tests..."
    coverage run --parallel-mode --module pytest

    # TODO: add conditional compilation and fix non-ani tests
    return

    for test_dir in $(find ../test/* -maxdepth 0 -type d -not -path "../test/ani_*" \
                           -and -not -path "../test/compiler" \
                           -and -not -path "../test/promise" \
                           -and -not -path "../test/impl_test"); do
        echo "Testing: $test_dir"
        coverage run --parallel-mode ./run-test "$test_dir" --generate-and-compile --generate-c-impl
    done
}

run-ani-tests
run-core-tests

# The coverage report will be generated by the EXIT trap
echo "Generating coverage report..."
